/**
 * 用户路由
 */

const querystring = require('querystring')
const { getList, getDetail, createUser, editUser, deleteUser, login } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const getCurrentTime = require('../util/getCurrentTime')
const { setRedis, getRedis } = require('../exec/execRedis')

const userRouterHandle = (req, res) => {
    // 解析req
    const path = req.url.split('?')[0]
    const method = req.method
    const getStr = req.url.split('?')[1]
    // 解析getStr
    const getData = querystring.parse(getStr)
    // 解析postData
    const postData = req.body
    // 用户列表
    if (method === 'GET' && path === '/api/user/list') {
        const keyword = getData.keyword
        const promise = getList(keyword)
        return promise.then(sqlData => {
            return new SuccessModel(sqlData, 'ok')
        })
    }
    // 用户详情
    if (method === 'GET' && path === '/api/user/detail') {
        const id = getData.id
        const promise = getDetail(id)
        return promise.then(sqlData => {
            return new SuccessModel(sqlData[0], 'ok')
        })
    }
    // 注册用户
    if (method === 'POST' && path === '/api/user/create') {
        const username = postData.username
        const realname = postData.realname
        const password = postData.password
        const currentTime = getCurrentTime()
        const promise = createUser(username, realname, password, currentTime, currentTime)
        return promise.then(sqlData => {
            if (sqlData.affectedRows && sqlData.insertId) {
                return new SuccessModel({
                    tip: '注册成功，id为：' + sqlData.insertId,
                    createTime: currentTime
                }, 'ok')
            } else {
                return new ErrorModel({
                    tip: '注册失败',
                    failTime: currentTime
                }, 'fail')
            }
        })
    }
    // 编辑用户
    if (method === 'POST' && path === '/api/user/edit') {
        const username = postData.username
        const realname = postData.realname
        const password = postData.password
        const currentTime = getCurrentTime()
        const id = getData.id
        const promise = editUser(username, realname, password, currentTime, id)
        return promise.then(sqlData => {
            if (sqlData.affectedRows) {
                return new SuccessModel({
                    tip: '修改成功',
                    updateTime: currentTime
                }, 'ok')
            } else {
                return new SuccessModel({
                    tip: '修改失败',
                    failTime: currentTime
                }, 'fail')
            }
        })
    }
    // 删除用户
    if (method === 'POST' && path === '/api/user/delete') {
        const id = getData.id
        const currentTime = getCurrentTime()
        const promise = deleteUser(id)
        return promise.then(sqlData => {
            if (sqlData.affectedRows) {
                return new SuccessModel({
                    tip: '删除成功',
                    deleteTime: currentTime
                }, 'ok')
            } else {
                return new SuccessModel({
                    tip: '删除失败',
                    failTime: currentTime
                }, 'fail')
            }
        })
    }
    // 用户登录
    if (method === 'POST' && path === '/api/user/login') {
        const username = postData.username
        const password = postData.password
        const currentTime = getCurrentTime()
        const promise = login(username, password)
        return promise.then(sqlData => {
            if (sqlData.length > 0) {
                return new SuccessModel({
                    tip: '登录成功',
                    loginTime: currentTime
                }, 'ok')
            } else {
                return new SuccessModel({
                    tip: '登录失败',
                    failTime: currentTime
                }, 'fail')
            }
        })
    }
    // 用户登录
    if (method === 'GET' && path === '/api/user/login') {
        const username = getData.username
        const password = getData.password
        const currentTime = getCurrentTime()
        const promise = login(username, password)
        return promise.then(sqlData => {
            if (sqlData.length > 0) {
                console.log('session', req.session)
                req.session.username = username
                req.session.password = password
                // 同步redis
                setRedis(req.userId, req.session)
                res.setHeader('Set-Cookie', `userId=${req.userId}; httpOnly; path=/`)
                // res.setHeader('Set-Cookie', [`username=${username}; httpOnly; path=/`, `password=${password}; httpOnly; path=/`])
                return new SuccessModel({
                    tip: '登录成功',
                    loginTime: currentTime
                }, 'ok')
            } else {
                return new SuccessModel({
                    tip: '登录失败',
                    failTime: currentTime
                }, 'fail')
            }
        })
    }
    // 登录验证
    if (method === 'GET' && path === '/api/user/login-test') {
        const currentTime = getCurrentTime()
        console.log('req.session', req.session)
        if (req.session.username) {
            return Promise.resolve(
                new SuccessModel({
                    tip: req.session.username + '登录成功',
                    checkTime: currentTime
                }, 'ok')
            )
        } else {
            return Promise.resolve(
                new ErrorModel({
                    tip: '尚未登录',
                    checkTime: currentTime
                }, 'fail')
            )
        }
    }
}

module.exports = userRouterHandle